<template>
  <el-dialog title="权限管理" :visible.sync="dialogVisible" width="30%" @close="handleClose">
    <el-tree
      ref="menuTreeRef"
      show-checkbox
      node-key="id"
      :data="menuList"
      :props="defaultProps"
      default-expand-all
      :default-checked-keys="defKeys"
    />
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { updateMenusByRoleId, getRoleMenuRoleId } from '@/api/other'
import { delateMenuChildren } from '@/config/publicMethod.js'
export default {
  data() {
    return {
      dialogVisible: false,
      roleId: '',
      menuList: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      defKeys: [],
    }
  },
  methods: {
    async init(item) {
      this.roleId = item.id
      const { code, data, msg } = await getRoleMenuRoleId({ rid: item.id })
      if (code !== '0000') return this.$message.error(msg)
      this.menuList = data
      this.defKeys = this.getLeafKeys(data)
      this.dialogVisible = true
    },
    // 通过递归的形式,获取角色下所有三级权限的id,并保存到defKeys
    getLeafKeys(node) {
      let arr = []
      const result = delateMenuChildren(node) // 去掉空数组
      result.forEach((el) => {
        if (el.children) {
          el.children.forEach((ele) => {
            if (ele.enabled) {
              arr.push(ele.id)
            }
          })
        } else {
          if (el.enabled) {
            arr.push(el.id)
          }
        }
      })
      return arr
    },
    handleClose() {
      this.defKeys = []
    },
    handleSubmit() {
      const ids = [
        ...this.$refs.menuTreeRef.getHalfCheckedKeys(),
        ...this.$refs.menuTreeRef.getCheckedKeys(),
      ]
      updateMenusByRoleId({ ids, roleId: this.roleId }).then((res) => {
        const { code, data, msg } = res
        if (code !== '0000') return this.$message.error(msg)
        this.dialogVisible = false
        this.$emit('updata')
      })
    },
  },
}
</script>

